package at.socialconference.web.server.util;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

import javax.imageio.ImageIO;

import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

public class QRCodeHelper {

	private static final int WIDTH = 300;
	private static final int HEIGHT = 300;

	public static void encode(String data, OutputStream outputStream) throws IOException{
		
		
		BitMatrix matrix;
		com.google.zxing.Writer writer = new QRCodeWriter();
		try {
			matrix = writer.encode(data, com.google.zxing.BarcodeFormat.QR_CODE, WIDTH, HEIGHT);
		}
		catch (com.google.zxing.WriterException e) {
			return;
		}

		int width = matrix.getWidth(); 
		int height = matrix.getHeight(); 

		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		for (int y = 0; y < height; y++) { 
			for (int x = 0; x < width; x++) { 
				boolean b = matrix.get(x, y);
				image.setRGB(x, y, (b ? 0 : 0xFFFFFF));
			}
		}
		if(outputStream!=null)
			ImageIO.write(image, "png", outputStream);
	}
	
}
